package yxy.cherry.paycenter.channelmodule.weixin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.joda.time.DateTime;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.channelmodule.PayMoudle_channel;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.util.HttpHelper;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.module.OrderInfoModule;
import yxy.game.pm2.bean.order.OrderInfo;
import yxy.game.pm2.bean.sdk.WeiXinOtherParm;

// 创建订单
public class PayMoudle_weixin extends PayMoudle_channel {
	
	static final Logger logger = Logger.create(PayMoudle_weixin.class);
	
	public static final int android = 1;
	public static final int ios = 2;
	
	public static final String mymd5key = "wx202105251533";
	
	private static String jh_order_checklogin = "https://pay.api.xjhgame.net/union/miniapp/order/submit";
	
	@Override
	public JSONObject dealPay(JSONObject infoobj) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public JSONObject createOrderInfo(JSONObject infoobj, orders o) {
		int system = infoobj.getIntValue("system");
		
		if(system == ios) {
			return createOrderInfoIos(infoobj, o);
		}
		
		return createOrderInfoAndroid(infoobj, o);
	}

	public void dealReportOrder(orders o) {
		//江湖下单处理
		//江湖验证
		
//		参数名	必选	类型	说明
//		appID	是	string	平台分配的应用id
//		json	是	string	json字符串，结构见：json结构
//		ext	是	string	保留字段，json字符串，固定填写：{}
//		sign	是	string	签名，签名规则请看签名规则
		
//		json结构
//		参数名	必选	类型	说明
//		simpleCode	是	string	渠道值，固定为：MINIAPP
//		uid	是	long	江湖平台uid
//		unionAppId	是	string	小程序appid
//		openUserId	是	string	小程序登录获取到的用户unionid/openid，如有unionid则填写unionid，否则填写openid
//		orderNo	是	string	接入方订单号
//		productNo	是	string	商品编号
//		amount	是	long	订单金额，单位：分
//		adId	是	string	小程序买量获取到的aid
		
		PlayerBean pb = PlayerBean.get(o.getPlayercode());
		WeiXinOtherParm wxop = WeiXinOtherParm.get(pb.getUid());
		String openid = wxop.getOpenid();
		String adId = wxop.getAdid() == null ? "" : wxop.getAdid();
		
		JSONObject jhjson = new JSONObject();
		jhjson.put("simpleCode", "MINIAPP");
		jhjson.put("uid", "");
		jhjson.put("unionAppId", SDKParm.getSdkparmvalue(SdkParmEnum.weixin_xcx_appid));			
		jhjson.put("openUserId", openid);
		jhjson.put("orderNo", o.getMyorderid());
		jhjson.put("productNo", o.getGoodsid());
		jhjson.put("amount", o.getGoodsprice());
		jhjson.put("adId", adId);
		
		String appID = SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_appid);
		String ext = "{}";

		//		签名规则
//		sign = md5 (appID + json + ext + OPENKEY);
//		//`OPENKEY`为平台分配。
		String jhsignstr = appID + jhjson + ext + SDKParm.getSdkparmvalue(SdkParmEnum.weixin_jh_openkey);  
		String jhsign = HttpUtil.getMD5(jhsignstr).toLowerCase();
		
		JSONObject jhpostjson = new JSONObject();
		jhpostjson.put("appID", appID);
		jhpostjson.put("json", jhjson);
		jhpostjson.put("ext", ext);
		jhpostjson.put("sign", jhsign);
		
		logger.info("jhpostjson " + jhpostjson);
		// 发送post请求
		String ret = "";
		try {				
			NameValuePair[] pair = HttpHelper.getValuePair(jhpostjson);
			ret = HttpHelper.doPost(jh_order_checklogin, pair, 30000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("ret " + ret);
//		if(ret == null || ret.equals("")) {
//			rjson.put("result", dataerror);
//			writeResponse(resp, rjson.toString());
//			return;
//		}
		
//		JSONObject retjson = JSON.parseObject(ret);
//		参数名	类型	说明
//		statusCode	string	“200”：表示成功，其他值表示接口失败
//		message	string	接口失败时的描述
//		orderNo	string	平台订单号
//		if(!retjson.containsKey("statusCode")) {
//			rjson.put("result", dataerror);
//			writeResponse(resp, rjson.toString());
//			return;
//		}
//		String statusCode = retjson.getString("statusCode");
//		
//		if(!statusCode.equals(jh_order_success)) {
//			rjson.put("result", dataerror);
//			writeResponse(resp, rjson.toString());
//			return;
//		}
		
	}
	
	//安卓
	public JSONObject createOrderInfoAndroid(JSONObject infoobj, orders o) {
		JSONObject parseobj = new JSONObject();
		long wxtime = System.currentTimeMillis();
		String wxmd5 = getToken(o.getPlayercode(), wxtime, mymd5key);
		parseobj.put("md5", wxmd5);
		parseobj.put("time", wxtime);
		o.setExt(wxmd5);
		ordersDao.update(o);
		dealReportOrder(o);
		return parseobj;
	}
	
	//ios
	public JSONObject createOrderInfoIos(JSONObject infoobj, orders o) {
		charge c = DataCenter.getData(o.getGoodsid(), charge.class);
		if(c == null) {
			return null;
		}
		
		String myiosorderid = getWxIosOrderId();
		o.setMyorderid(myiosorderid);
		ordersDao.update(o);
		
		String pcode = o.getPlayercode();
		PlayerBean pb = PlayerBean.get(pcode);
		
		JSONObject rjson = new JSONObject();
		String body = c.getName();			//商品简单描述，该字段请按照规范传递，具体请见参数规定
		String out_trade_no = o.getMyorderid();		//商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-|* 且在同一个商户号下唯一。详见商户订单号
		String product_id = String.valueOf(o.getGoodsid());
		String fee_type = "CNY";				//符合ISO 4217标准的三位字母代码，默认人民币：CNY，详细列表请参见货币类型
		int total_fee = c.getMoney();		//单位 分
		
		rjson.put("uid", pb.getUid());
		rjson.put("channel", o.getChannel());
		rjson.put("sid", o.getServerid());
		rjson.put("out_trade_no", out_trade_no);
		rjson.put("fee_type", fee_type);
		rjson.put("total_fee", total_fee);
		rjson.put("product_id", product_id);
		rjson.put("time", System.currentTimeMillis());
		rjson.put("code", o.getPlayercode());
		String signstr = HttpUtil.getSignData(rjson, null, null);
		signstr = signstr + "&key=" + SDKParm.getSdkparmvalue(SdkParmEnum.weixin_yuwan_apisecretkey);
		logger.info("PayMoudle_weixin signstr :" + signstr);
		String sign = HttpUtil.getMD5(signstr);
		rjson.put("sign", sign);
		
		logger.info("wx ios:" + rjson);
	
		dealReportOrder(o);
		return rjson;
	}
	
	public static String getToken(String playercode, long time, String secret) {
		String value = "code=%s&time=%s&secret=%s";
		value = String.format(value, playercode, String.valueOf(time), secret);
		String md5 = HttpUtil.getMD5(value);
		md5 = md5.toLowerCase();
		return md5;
	}
	
	public orders createOrderWeiXin(int dataid, String playercode, int serverid, int acttype) {	
		orders o = createOrder(getChannel(), dataid, acttype, playercode, serverid);
		addOrder(o);
		return o;
	}
	
	/**
	 * 创建 OrderInfo
	 * @param o
	 * @param curs
	 * @param c
	 * @param payamount
	 */
	public void createOrderInfoModule(orders o, ArrayList<Currency> curs, charge c, int payamount) {
		createOrderInfoModule(o, curs, c.getVipexp(), payamount);
	}
	
	/**
	 * 
	 * @param o
	 * @param curs
	 * @param vipexp
	 * @return
	 */
	public void createOrderInfoModule(orders o, ArrayList<Currency> curs, int vipexp, int payamount) {
		OrderInfo oi = OrderInfoModule.createOrderInfo(o.getGoodsid(), o.getChannel(), o.getMyorderid(), new DateTime(o.getCreatetime().getTime()), 
				OrderInfoModule.orderinforuning, o.getPlatorderid(), o.getActtype(), o.getPlayercode(), curs, 
				o.getServerid(), DateTime.now(), vipexp, payamount, o.getGoodsprice());
		OrderInfo.set(o.getPlayercode(), oi);
	}
	
	@Override
	public String getChannel() {
		return SdkChannel.sdk_weixin;
	}

	//ios 订单
	public static String getWxIosOrderId() {
		String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
		String seconds = new SimpleDateFormat("HHmmss").format(new Date());
		String orderid = "YDSGIOS" + date+getRandomOfSize(3)+seconds+getRandomOfSize(3);
		return orderid;
	}
}
